package com.lagou.service;

import com.lagou.pojo.Order;
import com.lagou.pojo.Result;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class MqService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    Map<String, Order> orderDataBase = new HashMap<>();
    List<String> expiredOrder = new ArrayList<>();

    public Result orderExpire(String orderId) {
        Result result = updateOrder(orderId, 2);
        if (result.getCode() == 0) {
            expiredOrder.add(orderId);
        }
        return result;
    }

    public Result createOrder(String orderId) {
        Order order = new Order();
        Result result = new Result();
        if (orderDataBase.containsKey(orderId)) {
            result.setFail("order id: "+orderId+" exist");
        } else {
            orderDataBase.put(orderId, order);
        }
        result.setSuccess("order id: " + orderId + " creates success");
        return result;
    }

    public Result payOrder(String orderId) {
        return updateOrder(orderId, 1);
    }

    private Result updateOrder(String orderId, int newState) {
        Result result = new Result();

        Order order = orderDataBase.get(orderId);
        if (order == null) {
            result.setFail("order id: "+orderId+" didn't exist");
            return result;
        }

        AtomicInteger state = order.getState();
        boolean b = state.compareAndSet(0, newState);
        if (!b) {
            int i = state.get();
            if (i == 1) {
                result.setFail("order id: "+orderId+" is already paid");
            } else {
                result.setFail("order id: "+orderId+" already expire");
            }
        } else {
            result.setSuccess("order id: " + orderId + " process success");
        }
        return result;
    }

    public void publishExpireMsg(String orderId) {
        rabbitTemplate.convertAndSend("ex.delayed", "key.delayed", orderId);
    }

    public List<String> findHistoryExpiredOrder() {
        return expiredOrder;
    }
}
